package com.atguigu.PracticalProject.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.PracticalProject.app.BaseAppV1;
import com.atguigu.PracticalProject.bean.UserLoginBean;
import com.atguigu.PracticalProject.common.Constant;
import com.atguigu.PracticalProject.util.AtguiguUtil;
import com.atguigu.PracticalProject.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsUserUserLoginWindow().init(
                3030,
                2,
                "DwsUserUserLoginWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        //1.找到用户登录记录
        SingleOutputStreamOperator<JSONObject> loginLogStream = findLoginLog(stream);

        //2.找到当日登录用户记录和7日回流用户记录
        SingleOutputStreamOperator<UserLoginBean> beanStream = findUVAndBack(loginLogStream);

        //3.开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);


        //4.写出到doris
        writeToDoris(resultStream);
    }

    private void writeToDoris(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream
                .map(bean -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; // 转成json的时候, 属性名使用下划线
                    return JSON.toJSONString(bean,config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("edu.dws_user_user_login_window"));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(new SerializableTimestampAssigner<UserLoginBean>() {
                            @Override
                            public long extractTimestamp(UserLoginBean element, long recordTimestamp) {
                                return element.getTs();
                            }
                        })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean bean1,
                                                UserLoginBean bean2) throws Exception {
                        bean1.setUuCt(bean1.getUuCt() + bean2.getUuCt());
                        bean1.setBackCt(bean1.getBackCt() + bean2.getBackCt());
                        return bean1;
                    }
                }
                , new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                            @Override
                            public void process(Context context,
                                                Iterable<UserLoginBean> iterable,
                                                Collector<UserLoginBean> collector) throws Exception {
                                UserLoginBean bean = iterable.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(context.window().getEnd()));

                                bean.setCurDate(AtguiguUtil.toDate(System.currentTimeMillis()));

                                collector.collect(bean);
                            }
                        }
                );

    }

    private SingleOutputStreamOperator<UserLoginBean> findUVAndBack(SingleOutputStreamOperator<JSONObject> loginLogStream) {
        return loginLogStream
                .keyBy(json -> json.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {

                    private ValueState<String> lastLoginDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastLoginDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject object,
                                               Context context,
                                               Collector<UserLoginBean> collector) throws Exception {
                        Long ts = object.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);

                        String lastLoginState = lastLoginDate.value();

                        Long uuCt = 0L;
                        Long backCt = 0L;
                        if (!today.equals(lastLoginState)) {
                            uuCt = 1L;
                            lastLoginDate.update(today);

                            if (lastLoginState != null) {
                                Long thisLoginTs = AtguiguUtil.toTs(today);
                                Long lastLoginTs = AtguiguUtil.toTs(lastLoginState);

                                if ((thisLoginTs - lastLoginTs) / 1000 / 60 / 60 / 24 > 7) {
                                    backCt = 1L;
                                }
                            }
                        }
                        if (uuCt == 1) {
                            collector.collect(new UserLoginBean(
                                    "", "",
                                    "",
                                    backCt, uuCt,
                                    ts
                            ));
                        }

                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> findLoginLog(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(obj -> {
                    String uid = obj.getJSONObject("common").getString("uid");
                    return uid != null;
                });
    }
}
